/*
 * 组件注释
 * @Author: machinist_wq
 * @Date: 2023-02-28 14:43:51
 * @LastEditors: machinist_wq
 * @LastEditTime: 2023-02-28 14:51:59
 * @Description: 字段排序
 * 既往不恋！当下不杂！！未来不迎！！！
 */
'use strict';
import { useState, forwardRef, useImperativeHandle, ForwardedRef } from 'react';
import { Space } from 'antd';
import { CaretDownOutlined, CaretUpOutlined } from '@ant-design/icons';

const SortFun = (props: { data: any; sort: any; type: any; }) => {
  const { data, sort, type } = props;
  return (
    <span
      onClick={() => sort(data.key, type || 0)}
      style={{
        fontSize: 12,
        cursor: "pointer",
      }}
    >
      {data.title}
      <span
        style={{
          position: "relative",
          marginLeft: 2,
          top: 4,
          fontSize: 10,
          display: "inline-block",
          width: 12,
          height: 17,
        }}
      >
        <span
          style={{
            position: "absolute",
            top: -4,
            left: 0,
            color: type === 1 ? "#266eed" : "rgba(0, 0, 0, 0.30)",
          }}
        >
          <CaretUpOutlined />
        </span>
        <span
          style={{
            position: "absolute",
            bottom: -4,
            left: 0,
            color: type === 2 ? "#266eed" : "rgba(0, 0, 0, 0.30)",
          }}
        >
          <CaretDownOutlined />
        </span>
      </span>
    </span>
  );
};

type value = 0 | 1 | 2
interface T {
  [key: string]: value
}

interface sortData {
  title: string,
  key: string,
}
interface IProps {
  dataSource: sortData[];
  onChange?: (arg0: T) => void,
  multiple?: boolean
}

const Index = forwardRef((props: IProps, ref: ForwardedRef<unknown>) => {

  const { dataSource, onChange, multiple } = props;

  const [initSortData] = useState<T>(() => {
    let sortDataMap: T = {}
    dataSource.forEach((item: sortData) => { sortDataMap[item.key] = 0 })
    return sortDataMap
  });

  const [sortSelectKeys, setSortSelectKeys] = useState<T>({});

  const sort = (key: string, type: number) => {
    const newType = (type + 1 > 2 ? 0 : type + 1) as value;
    if (multiple) {
      setSortSelectKeys({
        ...sortSelectKeys,
        [key]: newType,
      });
      onChange && onChange({
        [key]: newType,
      })
    }
    else {
      const sortSelectKeys = {
        ...initSortData,
        [key]: newType,
      }
      setSortSelectKeys(sortSelectKeys);
      onChange && onChange(sortSelectKeys)
    }

  };

  useImperativeHandle(ref, () => ({
    setSortSelectKeys,
  }));

  return <div className={"sort"}>
    <Space size="large">
      {dataSource.map((item) => {
        return (
          <SortFun
            type={sortSelectKeys[item.key]}
            key={item.key}
            data={item}
            sort={sort}
          />
        );
      })}
    </Space>
  </div>
});
export default Index;

/* dataSource={[
  {
    title: "发布时间",
    key: "assetPublishTime",
  },
]} */